package com.gitee.l0km.thrift.swift2thrift.generator;

import java.util.Locale;

import org.stringtemplate.v4.AttributeRenderer;

import com.gitee.l0km.codegen.annotations.CodegenLength;
import com.gitee.l0km.xthrift.base.metadata.DecoratorThriftFieldMetadata;
import com.gitee.l0km.xthrift.base.metadata.ThriftFieldMetadataUtil;

public class ErpcThriftFieldMetadataRenderer implements AttributeRenderer {
	private final ErpcTypeRenderer erpcTypeRenderer = new ErpcTypeRenderer();
	public ErpcThriftFieldMetadataRenderer() {
	}

	@Override
	public String toString(Object o, String formatString, Locale locale) {
		if(o instanceof DecoratorThriftFieldMetadata){
			DecoratorThriftFieldMetadata fieldMetadata = (DecoratorThriftFieldMetadata)o;
			 CodegenLength ann = ThriftFieldMetadataUtil.extractFieldAnnotation(fieldMetadata,CodegenLength.class);
			 if(ann != null && ann.prealloc()){
				 int len = ann.value();
				 if(len<=0){
					 len = ann.max();
				 }
				 if(len > 0){
					 return fieldMetadata.getErpcType().toPreAllocTypeString(len) ;	 
				 }	 
			 }
			 return erpcTypeRenderer.toString(fieldMetadata.getErpcType(), formatString, locale);
		}
		throw new IllegalArgumentException("UNSUPPORTED Renderer type " + o.getClass().getName() + " DecoratorThriftFieldMetadata required");
	}

}
